#include <iostream>
#include "SocketGlobals.h"
#include "SocketClient.h"
#include "SocketMan.h"

void         *global_sc = NULL;
void         *global_sm = NULL;
int           global_sm_or_sc = SC_GLOBAL_SWITCH;
int           global_sm_sys_v_signals = 0;
int           global_sigpipe_raised = 0;

void
handleSIGPIPE(int)
{
	cerr << "Caught SIGPIPE" << endl;

	if (global_sc && global_sm)
	{
		if (global_sm_or_sc == SC_GLOBAL_SWITCH)
		{
			((SocketClient *)global_sc)->closeConnection();
			cerr << "Closed connection to server (broken pipe)" << endl;
		}
		else
		{
			if (global_sm_or_sc == SM_GLOBAL_SWITCH)
			{
				((SocketMan *)global_sm)->deleteSocket();
				cerr << "Closed connection to client (broken pipe)" << endl;
			}
			else
			{
				cerr << "BUG: global_sm_or_sc was set improperly!" << endl;
			}
		}
	}
	else
	{
		if (global_sc)
		{
			((SocketClient *)global_sc)->closeConnection();
			cerr << "Closed connection to server (broken pipe)" << endl;
		}
		if (global_sm)
		{
			((SocketMan *)global_sm)->deleteSocket();
			cerr << "Closed connection to client (broken pipe)" << endl;
		}
	}

#ifndef WIN32
	if (global_sm_sys_v_signals)
		signal(SIGPIPE, handleSIGPIPE);
#endif

	global_sigpipe_raised = 1;
}
